<template>
  <el-dialog
    title="资产导入"
    v-model="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal-append-to-body="false"
    width="45%"
    top="15vh"
  >
    <div class="dialog-body">
      <el-form
        ref="form"
        :model="importForm"
        :rules="rules"
        class="strategyForm"
        label-width="120px"
        @submit.native.prevent
      >
        <el-form-item label="上传附件:" required>
          <div class="upload-wrap">
            <el-upload
              class="upload-demo"
              drag
              action="#"
              multiple
              :limit="6"
              :before-upload="beforeUpload"
              :on-change="change"
              :on-exceed="exceedFile"
              :on-remove="remove"
              :http-request="httpRequest"
            >
              <el-icon size="40"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处,
                或<em>点击上传</em>
              </div>
            </el-upload>
            <div class="tip-box">
              <div>
                提示：上传.xls/xlsx文件，且不超过200MB，
                <span @click="downloadTemplate">点击下载模版</span>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="添加标签:">
          <div class="tag-container">
            <div
              class="tag-box"
              v-for="(item, index) in importForm.tag"
              :key="index"
            >
              <span>{{ item.tag }}</span>
              <el-icon @click="handleClose(item.tag)"><Close /></el-icon>
            </div>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="$event.target.blur()"
              @blur="handleInputConfirm()"
            >
            </el-input>
            <div v-else class="new-tag" @click="showInput()">+ 新增</div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template v-slot:footer>
      <span class="dialog-footer">
        <el-button size="small" @click="cancel">取 消</el-button>
        <el-button type="primary" size="small" @click="confirm">确 定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup> 
import {defineProps,defineEmits,watch,ref,reactive,nextTick} from 'vue';
import {ElMessage} from 'element-plus';
import {useStore} from 'vuex';
const store =useStore()
const emit=defineEmits(['update:isShow'])
const props=defineProps({
  isShow: {
      type: Boolean,
      default: false,
    },
})
const visible=ref(props.isShow);
const inputVisible=ref(false);
const inputValue=ref('');
const fileList=ref([]);
const importForm=reactive<any>({
        filePaths: [],
        tag: [],
});
const saveTagInput=ref<any>(null)
const rules=ref({});
  watch(()=>visible.value,(newValue, oldValue)=>{
    emit('update:isShow', newValue)
  })
 const cancel=()=> {
      visible.value = false
    }

   const handleClose=(tag:any)=> {
      importForm.tag.splice(importForm.tag.indexOf(tag), 1)
    }
   const showInput=()=> {
      inputVisible.value = true
      nextTick(() => {
        if (saveTagInput.value) {
         saveTagInput.value.focus();
    }
      })
    }
   const handleInputConfirm=()=> {
      if (inputValue.value) {
        const foundObject = importForm.tag.find(
          (item) => item.tag === inputValue.value
        )

        if (foundObject) {
          return ElMessage.error('输入标签已存在')
        }

        importForm.tag.push({
          tag: inputValue.value,
        })
      }
      inputVisible.value = false
      inputValue.value = ''
    }



    // 文件下载
    // content: 后台返回的文件流， fileName： 文件名
    const downLoadFile=(content, fileName)=> {
      const blob = new Blob([content])
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        (navigator as any).msSaveBlob(blob, fileName)
      }
    }
    const downloadTemplate=async()=> {
      const res = await store.dispatch('api/templateDownload')
      if (!res) return

      downLoadFile(res, 'assetImport.zip')
      ElMessage.success('正在下载')
    }
   const beforeUpload=(file)=> {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const type =
        extension === 'xlsx' || extension === 'xls' || extension === 'csv'
      const size = file.size / 1024 / 1024 < 200

      if (!type) {
        ElMessage.error('上传文件只能是xlsx/xls/csv格式!')
      }
      if (!size) {
        ElMessage.error('上传文件大小不能超过 200MB!')
      }
      return type && size
    }
   const exceedFile=(files, fileList)=> {
      ElMessage.error('最多只能上传6个文件')
    }
   const change=(file, fileList)=> {}
   const remove=(file, fileList)=> {
      const arr = importForm.filePaths.filter(
        (item) => item.uid !== file.uid
      )
      importForm.filePaths = arr
    }
    const httpRequest=async(file)=> {
      const formData = new FormData()
      formData.append('file', file.file)
      const { code, data, message } = await store.dispatch(
        'api/uploadFile',
        formData
      )
      if (code !== 0) {
        ElMessage.error(message)
        return
      }
      importForm.filePaths.push({
        uid: file.file.uid,
        value: data,
      })
      ElMessage.success('上传成功')
    }
    const confirm=async()=> {
      if (!importForm.filePaths.length) {
        ElMessage.error('请上传文件')
        return
      }
      const tagStr = importForm.tag.map((item) => item.tag).join(',')
      const filePaths = importForm.filePaths.map((el) => el.value)
      const params = {
        filePaths: filePaths,
        tag: tagStr,
      }
      const { code, message } = await store.dispatch(
        'api/assetImport',
        params
      )
      if (code !== 0) {
        ElMessage.error(message)
        return
      }
      cancel()
    }
</script>
<style lang="scss" scoped>
.upload-wrap {
  display: flex;
  // align-items: center;

  .upload-demo {
    width: 260px;
    ::v-deep .el-upload-list__item-status-label {
      top: 5px;
    }
  }

  .tip-box {
    margin-top: 60px;
    font-size: 12px;
    margin-left: 20px;

    > div {
      line-height: 20px;
    }
    span {
      color: $-v-color-primary;
      cursor: pointer;
    }
  }
}

.tag-container {
  @include flexBox($justifyContent: flex-start);
  gap: $-v-spacing-horizontal-small; /* 设置子项之间的间距 */
  .tag-box {
    margin: 5px 8px;
    height: 24px;
    display: flex;
    align-items: center;
    padding: 2px 12px;
    background: rgba(210, 222, 235, 0.1);
    box-sizing: border-box;
    border: 0.5px solid rgba(210, 222, 235, 0.5);
    font-family: PingFang SC;
    font-size: 14px;
    font-weight: normal;
    border-radius: 4px;

    .tag-close {
      cursor: pointer;
      margin-left: 5px;
    }
  }
  .input-new-tag {
    min-width: 100px;
    max-width: 150px;
    // height: 24px;
  }

  ::v-deep .el-input--small .el-input__inner {
    height: 24px;
    line-height: 24px;
  }
  .new-tag {
    width: 66px;
    height: 24px;
    border-radius: 4px;
    box-sizing: border-box;
    border: 0.5px dashed #0289f7;
    font-size: 14px;
    font-weight: normal;
    line-height: 20px;
    color: #0289f7;
    cursor: pointer;
    text-align: center;
    margin: 0px 8px;
  }
}
</style>
